package cn.com.agree.mybatisporelation.one2one.oneside.service.impl;

import cn.com.agree.mybatisporelation.one2one.oneside.controller.dto.StudentDTO;
import cn.com.agree.mybatisporelation.one2one.oneside.dao.mapper.AddressMapper;
import cn.com.agree.mybatisporelation.one2one.oneside.dao.mapper.StudentMapper;
import cn.com.agree.mybatisporelation.one2one.oneside.dao.po.AddressPO;
import cn.com.agree.mybatisporelation.one2one.oneside.dao.po.StudentPO;
import cn.com.agree.mybatisporelation.one2one.oneside.service.StudentService;
import cn.com.agree.mybatisporelation.one2one.oneside.service.exception.BizException;
import cn.hutool.core.bean.copier.BeanCopier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private AddressMapper addressMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public StudentDTO addStudent(StudentDTO studentDTO) {
        AddressPO addressPO = BeanCopier.create(studentDTO.getAddress(), new AddressPO(), null).copy();
        addressMapper.insert(addressPO);

        StudentPO studentPO = BeanCopier.create(studentDTO, new StudentPO(), null).copy();
        studentPO.getAddress().setId(addressPO.getId());
        int rows = studentMapper.insert(studentPO);
        if (rows == 0) {
            throw new BizException("服务正忙，请稍后重试。");
        }

        return BeanCopier.create(studentPO, new StudentDTO(), null).copy();
    }

    @Override
    public StudentDTO getStudent(Long id) {
        StudentPO studentPO = studentMapper.selectById(id);
        if (Objects.isNull(studentPO)) {
            throw new BizException("学生信息不存在。");
        }
        return BeanCopier.create(studentPO, new StudentDTO(), null).copy();
    }

    @Override
    public StudentDTO getStudentAnotherWay(Long id) {
        StudentPO studentPO = studentMapper.findById(id);
        if (Objects.isNull(studentPO)) {
            throw new BizException("学生信息不存在。");
        }
        return BeanCopier.create(studentPO, new StudentDTO(), null).copy();
    }
}
